import moment from 'moment';

/**
 *   有关数据操作公共方法
 */

/**
 * 时间格式相关
 *  dateFormat   moment  =>  "2020-02-02"
 *  rangerFormat  [moment,moment]  => "2020-02-02 00:00:00,2020-02-02 23:59:59"
 */
// 对单个时间字段格式化处理,默认 YYYY-MM-DD
export const dateFormat = (date:any, format:any) => {
  if (!moment(date).isValid()) return date;
  return moment(date).format(!format ? 'YYYY-MM-DD' : format);
};
// 对区间两个时间字段格式化处理,并把结果用逗号拼接  默认YYYY-MM-DD HH:mm:ss
export const rangerFormat = (date:any, startFormat:any, endFormat:any) => {
  const [startTime, endTime] = date;
  if (!moment(startTime).isValid()) return startTime;
  if (!moment(endTime).isValid()) return endTime;
  return `${moment(startTime).format(!startFormat ? 'YYYY-MM-DD HH:mm:ss' : startFormat)},${moment(
    endTime,
  ).format(!endFormat ? 'YYYY-MM-DD HH:mm:ss' : endFormat)}`;
};

/**
 * 过滤方法
 *  "a"  ["a","b"]  => true
 */
export const filterAuth = (auth:any, permissions:any,pathname='') => auth.startsWith('/')?permissions.includes(auth) : permissions.includes(pathname+'/'+auth);

/**
 * 数组过滤方法
 *  ["a"]  [{ key:"a"},{ key:"b"}]  => [{key:"a"}]
 */
export const filterBtns = (auth = [], btns = []) => btns.filter((item:any) => auth.includes(item.key));

/**
 *  数据字典数据获取
 *
 */
export const getDicByKey = (data:any, code:any, key:any) => {
  let newData = data.filter((item:any)=>item.dictCode == code);
  return data && newData
  ? newData.find((d:any) => d.dictKey === key)
    ? newData.find((d:any) => d.dictKey === key).dictValue
    : key
  : key;
}

/**
 *  通过Code获取数组
 */
export const findDicByCode = (data:any, code:any) => {
  return data && data.filter((item:any)=>item.dictCode == code) ? data.filter((item:any)=>item.dictCode == code) : [];
}

export const findDicByCodeSort = (data:any, code:any) => {
  return data && data.filter((item:any)=>item.dictCode == code) ? data.filter((item:any)=>item.dictCode == code).sort((a:any, b:any) => a.dictSort - b.dictSort) : [];
}

export const comboHolder = (label:any) => {
  return '请输入' + label;
}

export const comboSelectHolder = (label:any) => {
  return '请选择' + label;
}

/**
 * 通过code获取字典options数组
 * @param data dictData 数据字典数组
 * @param dictCode 字典code
 * @returns
 */
export const getDictOptionsByCode = (data: Array<any>, dictCode: string) => {
  return data
    .filter((d: any) => d.dictCode === dictCode)
    ?.map((item: { dictValue: any; dictKey: any }) => {
      return {
        value: item.dictKey,
        label: item.dictValue,
      };
    });
};
